<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>二维码生成器</title>
    <style>
      .item {
        margin: 10px 0;
      }
    </style>
  </head>
  <body>
    <div class="item">
      从第几行开始
      <input id="row" type="text" value="2" />
    </div>
    <div class="item">
      从第几列开始
      <input id="col" type="text" value="7" />
    </div>
    <div class="item">
      选择 Excel 表格
      <input
        type="file"
        accept=".xls,.xlsx"
        multiple
        onchange="fileChange(this)"
      />
    </div>

    <script>
      const fs = require("fs");
      const xlsx = require("node-xlsx");
      const qr = require("qr-image");
      const { shell } = require("electron").remote;

      const fileChange = (fileInput) => {
        // 指定需要生成二维码的列
        const startRow = document.querySelector("#row").value;
        const startCol = document.querySelector("#col").value;

        const files = fileInput.files;
        if (files.length <= 0) return;

        // 创建输出根文件夹
        const firstFilePath = files[0].path;
        const outputPath = `${firstFilePath.substr(
          0,
          firstFilePath.lastIndexOf("\\")
        )}/output${new Date().getTime()}`;
        if (!fs.existsSync(outputPath)) {
          fs.mkdir(outputPath, () => {});
        }

        for (let i = 0; i < files.length; i++) {
          const { path: filePath, name: fileName } = files[i];

          const folderName = fileName.substr(0, fileName.lastIndexOf("."));
          // 创建对应文件的输出路径
          const fileOutputPath = `${outputPath}/${folderName}`;
          if (!fs.existsSync(fileOutputPath)) {
            fs.mkdir(fileOutputPath, () => {});
          }

          // 解析文件
          let sheetList = xlsx.parse(filePath);

          sheetList.forEach((sheet) => {
            // 根据工作表名称创建文件夹
            const sheetName = sheet.name;
            const sheetOutputPath = `${fileOutputPath}/${sheetName}`;
            if (!fs.existsSync(sheetOutputPath)) {
              fs.mkdir(sheetOutputPath, () => {});
            }

            // 处理单张工作表
            sheet.data.forEach((row, rowIndex) => {
              if (rowIndex < startRow - 1) return;

              const cardNum = row[startCol - 1];
              if (!cardNum || cardNum == "积分卡号") return;

              const code2img = qr.image(cardNum + "", {
                size: 10,
                margin: 0,
              });
              code2img.pipe(
                fs.createWriteStream(`${sheetOutputPath}/${cardNum}.png`)
              );
            });
          });
        }

        fileInput.value = "";
        alert("解析完成");
        shell.openPath(outputPath);
      };
    </script>
  </body>
</html>
